/**
 * 
 */
package cc.rico.jms.p2p.sender;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cc.rico.jms.utils.ActiveMQConnectionUtils;

/**
 * 生产者
 * @author rico 2016年8月1日
 *
 */
public class SimpleProductor {
	private static final Logger logger = LoggerFactory.getLogger(SimpleProductor.class);
	
	private MessageProducer producer;
	private Session session;
	private Connection connection;
	
	private boolean isOpen = true;
	//private Destination replyTo = null;
	
	public SimpleProductor() {
		try {
			//ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.223.137:61616");
			//connection = connectionFactory.createConnection();
			connection = ActiveMQConnectionUtils.createQueueConnection();
			
			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			Destination destination = session.createQueue("queue1");
			//replyTo = session.createQueue("queue2");
			producer = session.createProducer(destination);
			producer.setDeliveryMode(DeliveryMode.PERSISTENT);
			connection.start();
			
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

	
	public synchronized void sendMessage(String msg) {
		if(!isOpen) {
			logger.error("connection is closed");
		}
		
		try {
//			Message message = session.createTextMessage(msg);
//			//String cid = System.currentTimeMillis() + "";
//			//message.setJMSCorrelationID(cid);
//			producer.send(message);
//			logger.info("##sendMessage.msg={}", msg);
			
			for(int i=0; i<10; i++) {
				Message message = session.createTextMessage(msg.concat("-").concat(i+""));
				producer.send(message);
				logger.info("##sendMessage.msg={}", msg);	
			}
			//producer.close();
			
//			MessageConsumer consumer = session.createConsumer(replyTo, "JMSCorrelationID='" + cid + "'");
//			for(int i=0; i<5; i++) {
//				Message receiveMsg = consumer.receive(30000);
//				if(receiveMsg != null) {
//					logger.info("receiveMsg={}", ((TextMessage)receiveMsg).getText());
//					break;
//				}
//			}
//			
//			consumer.close();
			
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}
	
	public synchronized void close() {
		try {
			if(isOpen) {
				isOpen = false;
				session.close();
				connection.close();
			}
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}
	
}
